<template>
  <div class="material-report-container">
    <!-- 顶部筛选区 -->
    <div class="filter-container">
      <el-card shadow="hover" class="filter-card">
        <el-form :inline="true" :model="filterForm" label-width="70px">
          <!-- 第一行 -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="物料代码">
                <el-select multiple v-model="filterForm.skuID" placeholder="请选择物料信息" clearable remote
                  :remote-method="searchSelectNccMaterial" filterable>
                  <el-option v-for="item in materialNameOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="查询条件">
                <el-switch v-model="filterForm.modeCode" active-text="按编码" inactive-text="按名称" :active-value="1"
                  :inactive-value="0"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="批次号">
                <div style="display: flex; gap: 8px; width: 100%;">
                  <el-input clearable v-model="filterForm.batchNo" placeholder="请输入批次号" style="flex: 1;"></el-input>
                  <el-dropdown @command="handleCommandCode" trigger="click">
                    <span class="el-dropdown-link">
                      {{btnCode}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="0">全部</el-dropdown-item>
                      <el-dropdown-item command="1">等于</el-dropdown-item>
                      <el-dropdown-item command="2">不等于</el-dropdown-item>
                      <el-dropdown-item command="3">包含</el-dropdown-item>
                      <el-dropdown-item command="4">不包含</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物资类别">
                <el-select multiple clearable filterable v-model="filterForm.skuClassId" placeholder="请选择物资类别">
                  <el-option v-for="(item, index) in typeData" :key="index" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 操作按钮 -->
                <el-form-item>
                  <div>
                    <el-button type="primary" icon="el-icon-search" @click="fetchBasicData">查询</el-button>
                    <el-button type="primary" icon="el-icon-download" @click="exportExcel">导出excel</el-button>
                    <el-button type="primary" icon="el-icon-download" @click="exportPdf">导出pdf</el-button>
                    <el-button type="primary" icon="el-icon-download" @click="exportCsv">导出CSV</el-button>
                    <el-button type="danger" icon="el-icon-refresh" @click="resetFilter">重置</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!-- 主内容区 -->
    <div class="main-content">
      <el-table :key="tableKey" :summary-method="getSummaries" show-summary height="calc(100vh - 215px)" :data="sluggishStatistic"
        border style="width: 100%">
        <el-table-column prop="ClassName" label="物资类别" />
        <el-table-column prop="Sku_Code" label="物料代码" />
        <el-table-column prop="GMP_Bar" label="GMP码" />
        <el-table-column prop="SenderCode" label="供应商代码" />
        <el-table-column prop="sto_unit_id" label="货位号" />
        <el-table-column prop="Sku_Name" label="物料名称" />
        <el-table-column prop="materialspec" label="规格" />
        <el-table-column prop="vbatchcode" label="批号" />
        <el-table-column prop="cunit_name" label="单位" />
        <el-table-column prop="unqualified_num" label="入库数量" />
        <el-table-column prop="InventoryNum" label="数量" />
        <el-table-column prop="operator" label="经办人" />
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination background layout=" total,prev, pager, next, sizes,jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="filterForm.pageNum" :page-size="filterForm.pageSize"
        :page-sizes="[20, 50,100]" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import {
    informationType, //获取物料类型
  } from "@/api/index/warehouse";
  import BasicStatistics from './components/BasicStatistics'
  import {
    wmsReportUnqualifiedStatistic, //获取统计数量
    getnccMaterial, //获取物料
  } from '@/api/report/allNews'
  export default {
    name: 'MaterialReport',
    components: {
      BasicStatistics,
    },
    data() {
      return {
        tableKey: Date.now(), // 用于强制刷新表格
        btnCode: '全部',
        filterForm: {
          skuID: [], //商品
          skuClassId: [], //物料类别
          wareHouseID: [], //仓库
          batchNo: '', //批号
          sluggishBegin: '', //呆滞开始
          sluggishEnd: '', //呆滞结束
          batchNoValue: 0, //0等于任意一个 1等于 2不等于 3包含 4不包含
          pageNum: 1,
          pageSize: 20,
          modeCode: 0
        },
        // 数据加载状态
        basicLoading: false,
        // 数据
        sluggishStatistic: [],
        warehousesList: [], //仓库下拉
        typeData: [], //下拉选择物料类型
        total: 0,
        materialNameOptions: [],
        totalSum: 0,
        un_total:0,//不合格总数
      }
    },
    created() {
      this.fetchBasicData();
      this.getType();
    },
    methods: {
      //导出excel
      exportExcel(){
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          skuClassId: this.filterForm.skuClassId.join(','), //物料类别
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          batchNo: this.filterForm.batchNo, //批号
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          sluggishBegin: this.filterForm.sluggishBegin,
          sluggishEnd: this.filterForm.sluggishEnd, //呆滞结束
          modeCode: this.filterForm.modeCode,
          pageNum: this.filterForm.pageNum,
          pageSize: this.filterForm.pageSize,
        };
        this.download('stoUnit/exportReportUnqualifiedStatistic', {
          ...params
        }, `不合格品台账.xlsx`)
      },
      //导出pdf
      exportPdf(){
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          skuClassId: this.filterForm.skuClassId.join(','), //物料类别
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          batchNo: this.filterForm.batchNo, //批号
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          sluggishBegin: this.filterForm.sluggishBegin,
          sluggishEnd: this.filterForm.sluggishEnd, //呆滞结束
          modeCode: this.filterForm.modeCode,
          pageNum: this.filterForm.pageNum,
          pageSize: this.filterForm.pageSize,
        };
        this.download('stoUnit/exportPdfReportUnqualifiedStatistic', {
          ...params
        }, `不合格品台账.pdf`)
      },
      //导出csv
      exportCsv(){
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          skuClassId: this.filterForm.skuClassId.join(','), //物料类别
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          batchNo: this.filterForm.batchNo, //批号
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          sluggishBegin: this.filterForm.sluggishBegin,
          sluggishEnd: this.filterForm.sluggishEnd, //呆滞结束
          modeCode: this.filterForm.modeCode,
          pageNum: this.filterForm.pageNum,
          pageSize: this.filterForm.pageSize,
        };
        this.download('stoUnit/exportCsvReportUnqualifiedStatistic', {
          ...params
        }, `不合格品台账.csv`)
      },
      //合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];

        // 处理空数据情况
        if (data.length === 0) {
          columns.forEach((column, index) => {
            sums[index] = index === 0 ? '合计' : '无数据';
          });
          return sums;
        }

        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }

          if (column.property === 'InventoryNum') {
            const currentPageSum = data.reduce((sum, item) => {
              return sum + (Number(item[column.property]) || 0);
            }, 0);

            // 使用this.totalSum而不是param中的数据
            sums[index] = `当前:${currentPageSum}/总:${this.totalSum || 0}`;
          }else if (column.property === 'unqualified_num') {
            const currentPageSum = data.reduce((sum, item) => {
              return sum + (Number(item[column.property]) || 0);
            }, 0);

            // 假设另一个字段的总和存储在this.anotherTotalSum中
            sums[index] = `当前:${currentPageSum}/总:${this.un_total || 0}`;
          } else {
            sums[index] = '-';
          }
        });

        return sums;
      },
      // 格式化时间
      formatDate(date) {
        if (!date) return ''; // 如果 `date` 为空或 `null`，返回占位符
        return this.$dayjs(date).isValid() ? this.$dayjs(date).format('YYYY-MM-DD') : '-';
      },
      // 远程搜索函数 获取NCC物料信息
      searchSelectNccMaterial(query) {
        if (query !== '') {
          const params = {
            materialName: query, // 传入输入的关键字
            modeCode: this.filterForm.modeCode, // 传入输入的关键字
          };
          // 调用接口进行物料信息查询
          getnccMaterial(params)
            .then(response => {
              if (response.code === 200) {
                // 更新物料选项
                this.materialNameOptions = response.data
              } else {
                this.materialNameOptions = [];
              }
            })
            .catch(error => {
              console.error('查询物料信息失败:', error);
              this.materialNameOptions = [];
            })
            .finally(() => {});
        } else {
          this.materialNameOptions = [];
        }
      },
      //分页
      handleSizeChange(val) {
        this.filterForm.pageSize = val;
        this.filterForm.pageNum = 1;
        this.fetchBasicData();
      },
      handleCurrentChange(val) {
        this.filterForm.pageNum = val;
        this.fetchBasicData();
      },
      //获取存放商品类型
      getType() {
        informationType().then(res => {
          this.typeData = res.data;
        })
      },
      handleCommandCode(command) {
        if (command == 0) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '全部';
          this.fetchBasicData();
        } else if (command == 1) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '等于';
          this.fetchBasicData();
        } else if (command == 2) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '不等于';
          this.fetchBasicData();
        } else if (command == 3) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '包含';
          this.fetchBasicData();
        } else {
          this.filterForm.batchNoValue = command;
          this.btnCode = '不包含';
          this.fetchBasicData();
        }
      },
      resetFilter() {
        this.filterForm = {
          skuID: [], //商品
          skuClassId: [], //物料类别
          wareHouseID: [], //仓库
          batchNo: '', //批号
          sluggishBegin: '', //呆滞开始
          sluggishEnd: '', //呆滞结束
          batchNoValue: 0, //0等于任意一个 1等于 2不等于 3包含 4不包含
          pageNum: 1,
          pageSize: 20,
          modeCode: 0
        }
        this.fetchBasicData()
      },
      async fetchBasicData() {
        this.basicLoading = true;
        try {
          const params = {
            skuID: this.filterForm.skuID.join(','), //商品
            skuClassId: this.filterForm.skuClassId.join(','), //物料类别
            wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
            batchNo: this.filterForm.batchNo, //批号
            batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
            sluggishBegin: this.filterForm.sluggishBegin,
            sluggishEnd: this.filterForm.sluggishEnd, //呆滞结束
            modeCode: this.filterForm.modeCode,
            pageNum: this.filterForm.pageNum,
            pageSize: this.filterForm.pageSize,
          };
          const res = await wmsReportUnqualifiedStatistic(params);

          this.sluggishStatistic = res.data.rows || [];
          this.total = res.data.total;
          this.un_total = this.totalSum = res.data.un_total_quantity ||
            (res.data.rows.length > 0 ? res.data.rows[0].un_total_quantity : 0);
          // 安全获取全局合计（优先从res.data取，其次从rows[0]取）
          this.totalSum = res.data.total_quantity ||
            (res.data.rows.length > 0 ? res.data.rows[0].total_quantity : 0);

          this.tableKey = Date.now(); // 强制刷新表格
        } catch (error) {
          console.error('获取数据失败:', error);
          this.$message.error('获取数据失败');
        } finally {
          this.basicLoading = false;
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  .material-report-container {
    padding: 16px;
    background-color: #f5f7fa;
  }

  .filter-container {
    margin-bottom: 16px;
  }

  .filter-card {
    border-radius: 4px;
  }

  .range-inputs {
    display: flex;

    ::v-deep .el-input--medium .el-input__inner {
      width: 135px;
    }
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    display: flex;
    align-items: center;
  }

  .el-dropdown-link i {
    margin-left: 4px;
  }

  .el-form-item__label {
    padding-right: 8px;
  }

  .main-content {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
</style>
